<?php

class Application {
	protected $requestPath;
	
	public function __construct() {
		$this->requestPath = Utils::vget($_GET, 'p');
	}
	
	public function run() {
		$controller = $this->getController();
		$action = $this->getAction();
		$actionMethod = 'action'.ucfirst($action);
		
		if ($controller && method_exists($controller, $actionMethod)) {
			$params = $this->getParams();
			
			return call_user_func_array(array($controller, $actionMethod), $params);
		}
		
		throw new Exception("No controller/action found");
	}
	
	public function getController() {
		$parts = explode('/', $this->requestPath);
		$controllerName = $parts[0] ?: 'index';
		$controllerClass = ucfirst($controllerName).'Controller';
		
		return class_exists($controllerClass) ? new $controllerClass() : null;
	}
	
	public function getAction() {
		return Utils::vget(explode('/', $this->requestPath), 1, 'index');
	}
	
	public function getParams() {
		return array_slice(explode('/', $this->requestPath), 2);
	}
}
